﻿using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using FluentAvalonia.UI.Controls;
using LiveHub.AvaloniaApp.Models;
using LiveHub.AvaloniaApp.ViewModels.Pages;
using LiveHub.DataModels;

namespace LiveHub.AvaloniaApp.Views;

public partial class MainView : UserControl
{
    public readonly Dictionary<string, PageModelBase> Stack = [];

    private NavigationViewItem? _currentItem;

    public MainView(string jwt, UserModel user)
    {
        Stack.Add("Friend", new FriendViewModel());
        Stack.Add("Setting", new SettingViewModel());
        Stack.Add("Help", new HelpViewModel());
        foreach (var group in user.Groups)
        {
            Stack.Add("Chat-" + group.GroupId, new ChatViewModel(jwt, user, group));
        }

        InitializeComponent();

        FrameView.NavigationPageFactory = new NavigationFactory();
        var list = new List<object>();
        list.AddRange(NavView.MenuItems);
        list.AddRange(user.Groups.Select(group => new NavigationViewItem()
        {
            Content = group.Name, Tag = "Chat-" + group.GroupId,
            IconSource = new BitmapIconSource(){UriSource = new Uri("avares://LiveHub.AvaloniaApp/Assets/iOS_Club_LOGO.png")}
        }));
        NavView.MenuItems = list;
    }

    private void ItemInvoked(object? sender, NavigationViewItemInvokedEventArgs e)
    {
        if (e.InvokedItemContainer.Tag is not string s) return;
        if (e.InvokedItemContainer is not NavigationViewItem item) return;
        if (item.IconSource is SymbolIconSource icon)
        {
            icon.Symbol = GetSymbol(icon.Symbol, false);

            if (_currentItem is { IconSource: SymbolIconSource _currentIcon })
                _currentIcon.Symbol = GetSymbol(_currentIcon.Symbol);
        }

        Navigate(s);

        _currentItem = item;
    }

    private static Symbol GetSymbol(Symbol page, bool isPre = true)
    {
        var iconString = page.ToString();
        if (isPre)
        {
            if (iconString.Contains("Filled")) iconString = iconString.Replace("Filled", "");
        }
        else
        {
            if (!iconString.Contains("Filled")) iconString += "Filled";
        }

        return Enum.TryParse<Symbol>(iconString, out var symbolIcon) ? symbolIcon : page;
    }

    private void Navigate(string page)
    {
        if (string.IsNullOrEmpty(page)) return;
        Navigate(Stack[page]);
    }

    public void NavigateFirstChat()
    {
        Navigate("Chat-iOS Club");
    }

    private void Navigate(object context)
    {
        FrameView.NavigateFromObject(context);
    }
}